package util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;
//dbcp连接池
public class DBUtil {
	//连接池类型
	private static DataSource ds;
	//事务处理时共用一个conn
	private static ThreadLocal<Connection> connLocal = new ThreadLocal<Connection>();
	
	static{
		try {
			Properties props = new Properties();
			InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("util/dbcp.properties");
			props.load(in);
			ds=BasicDataSourceFactory.createDataSource(props);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnction() throws Exception{
		//先从threadlocal中取得conn
		Connection conn = connLocal.get();
		//如果conn为空或者连接被关闭了，说明第一次连接，新建一个conn
		if(conn==null || conn.isClosed()){
			conn=ds.getConnection();
			//把conn设置到线程中
			connLocal.set(conn);
		}
		//已经创建conn,就直接返回
		return conn;
	}
	
	public static void close(){
		Connection conn = connLocal.get();
		if(conn!=null){
			try {
				conn.close();//放回连接池
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) throws Exception{
		System.out.println(DBUtil.getConnction().hashCode());
		System.out.println(DBUtil.getConnction().hashCode());
		System.out.println(DBUtil.getConnction().hashCode());
	}
}
